import * as base from './base.js'; //引入请求地址
import * as rest from './rest.js';
import {
	loginPage
} from "@/util/publicConfig"; //引入公共方法

const setToken = token => {
	uni.setStorageSync('baseToken', token);
}

const getToken = () => {
	try {
		const token = uni.getStorageSync('baseToken');
		return token;
	} catch (e) {
		return '';
	}
};

const getQueryHeaders = () => {
	return {
		'X-Access-Token': getToken()
	}
}

// 请求方式的封装地址，请求方法,请求参数，请求头，是否开启错误提示,接口是否携带token
function request(url, method, data, header, tips) {
	return new Promise((resolve, reject) => {
		if (!tips) {
			// 加载动画
			rest.tips("showload", '加载中')
		}

		// 参数,固定参数
		var datas = Object.assign(data, {})
		// uniapp的请求
		uni.request({
			url: url,
			data: Object.keys(datas).length > 0 ? datas : null,
			header: header,
			method: method,
			success: (res) => {
				// 隐藏当前加载动画
				rest.tips("hideload");
				// 如果传入tips参数为空，或者不传说明要判断
				if (!tips || tips == '') {
					// 如果请求失败
					if (res.data.code == 200) {
						// 请求成功的返回值
						resolve(res.data.result);
					} else if (res.data.code == 401) {
						rest.tips("showtoast", '请重新登录', '', 'error');
						uni.redirectTo({
							url: loginPage
						})
					} else {
						// 提示请求失败的原因，根据字符判断使用的弹窗
						rest.tips("showtoast", res.data.message, '', 'error');
						reject()
					}
				} else {
					// 判断tips的参数
					resolve(res.data)
				}
			},
			fail: (err) => {
				// 隐藏当前加载动画
				rest.tips("hideload");
				rest.tips("showtoast", "请求失败", '', 'error');
			}
		});
	})
}

// post请求
function requestPost({
	url,
	data,
	header = {
		openId: rest.cache('g', 'openid')
	},
	tips
}) {
	return request(base.baseUrl + url, "POST", data || {}, header, tips)
}

// put请求
function requestPut({
	url,
	data,
	header = {
		openId: rest.cache('g', 'openid')
	},
	tips
}) {
	return request(base.baseUrl + url, "PUT", data || {}, header, tips)
}

// get请求
function requestGet({
	url,
	data,
	header = {
		openId: rest.cache('g', 'openid')
	},
	tips
}) {
	return request(base.baseUrl + url, "GET", data || {}, header, tips)
}
// get请求
function requestGet1({
	url,
	data,
	header = {
		openId: rest.cache('g', 'openid')
	},
	tips
}) {
	return request(base.baseUrl1 + url, "GET", data || {}, header, tips)
}

function baseRequestGet({
	url,
	data
}) {
	return request('https://xcq.ldyw.vc14.com:8185/jeecg-boot' + url, "GET", data || {}, )
}

// get请求
function requestDelete({
	url,
	data,
	header = {
		openId: rest.cache('g', 'openid')
	},
	tips
}) {
	return request(base.baseUrl + url, "DELETE", data || {}, header, tips)
}

export {
	baseRequestGet,
	requestPost, //post请求
	requestPut, //请求
	requestGet,
	requestGet1,
	requestDelete,
	setToken,
	getToken,
	getQueryHeaders
}